package com.example.hs.Service;


import com.example.hs.Pojo.Recycler;
import com.example.hs.Repository.RecyclerRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RecyclerService {
    @Autowired
    private RecyclerRepository recyclerRepository;

    public Recycler register(Recycler recycler) {
        if (recyclerRepository.existsBynum(recycler.getNum())) {
            return null;
        }
        return recyclerRepository.save(recycler);
    }

    public Recycler login(Long num, String password, HttpSession session) {
        Recycler recycler= recyclerRepository.findByNumAndPassword(num, password);
        if (recycler != null) {
            session.setAttribute("recycler", recycler);
            return recycler;
        } else {
            throw new RuntimeException("Invalid credentials");
        }
    }

    public void logout(HttpSession session) {
        session.invalidate(); // 使Session失效
    }


    public List<Recycler> getAllRecyclers() {
        return recyclerRepository.findAll();
    }

    public Recycler updateRecycler(HttpSession session, Recycler updatedRecycler) {
       Recycler recycler = (Recycler) session.getAttribute("recycler");
       recycler.setUsername(updatedRecycler.getUsername());
       recycler.setNum(updatedRecycler.getNum());
       recycler.setAvatar(updatedRecycler.getAvatar());
       return recyclerRepository.save(recycler);
    }

    public Recycler getProfile(HttpSession session) {
        Recycler Recycler = (Recycler) session.getAttribute("recycler");
        return recyclerRepository.findById(Recycler.getRecyclerId()).orElse(null);
    }
}
